package com.edu.labmanager.controller;


import com.edu.labmanager.common.MyUserDetails;
import com.edu.labmanager.entity.*;
import com.edu.labmanager.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户表，存储系统用户的登录信息和角色权限 前端控制器
 * </p>
 *
 * @author author
 * @since 2025-06-15
 */
@Controller
@Slf4j
@RequestMapping("/user")
public class UserController {
    @Autowired
    private IUserService  userService;
    @Autowired
    private PasswordEncoder bCryptPasswordEncoder;
    @Autowired
    private IUserinfoService userinfoService;
    @Autowired
    private CommonService commonService;
    @Autowired
    private ILaboratoryService laboratoryService;
    @Autowired
    private ILabAdminManagementService iLabAdminManagementService;
    @Autowired
    private ITermService termService;


    @RequestMapping("/login")
    public String login(){
        return "login";
    }
    @RequestMapping("/loginFail")
    public String loginFail(){
        return "loginFail";
    }
    /**
     * 注册
     * @return
     */

    @RequestMapping("/register")
    public String register(){
        return "register";
    }
    @RequestMapping("/noauth")
    public String noauth(){
        return "noauth";
    }
    //注册功能
    @PostMapping("/register")
    public String register(@RequestParam String username, @RequestParam String password) {
        User user = new User();
        String password1 = bCryptPasswordEncoder.encode(password);
        user.setUserName(username);
        user.setPassword(password1);
        user.setRole("ROLE_USER");
        userService.save(user);

        UserInfo userInfo = new UserInfo();
        userInfo.setUserId(user.getUserId());
        userInfo.setEmail("");
        userInfo.setPhoneNumber("");
        userInfo.setImage("");
        userinfoService.save(userInfo);
        log.info("用户注册成功");
        return "login";
    }
    @GetMapping("index")
    public String index(Authentication authentication, Model model){
//        MyUserDetails userDetails = (MyUserDetails) authentication.getPrincipal();
//        model.addAttribute("user", userDetails);
//        List<Integer> labIds = iLabAdminManagementService.query().eq("user_id", userDetails.getId()).list()
//                .stream().map(LabAdminManagement::getLaboratoryId).collect(Collectors.toList());
//
//        if (!labIds.isEmpty()){
//            List<Laboratory> laboratories = laboratoryService.listByIds(labIds);
//            Map<Integer, String> labMap = laboratories.stream().collect(Collectors.toMap(Laboratory::getLaboratoryId, Laboratory::getLaboratoryName));
//            model.addAttribute("labMap",labMap);
//        }else{
//            model.addAttribute("labMap", Collections.emptyMap());
//        }
//        model.addAttribute("termMap",termService.list().stream().collect(Collectors.toMap(Term::getTermId, Term::getTermName)));

        return "index";
    }
    @GetMapping("/userInfo")
    public String userInfo(Authentication authentication, Model model){
        MyUserDetails userDetails = (MyUserDetails) authentication.getPrincipal();
        log.info("用户名：{}", userDetails.getUsername());
        model.addAttribute("userDetails", userDetails);
        model.addAttribute("userInfo", userinfoService.lambdaQuery().eq(UserInfo::getUserId,userDetails.getId()).one());

        List<Integer> labIds = iLabAdminManagementService.query().eq("user_id", userDetails.getId()).list()
                .stream().map(LabAdminManagement::getLaboratoryId).collect(Collectors.toList());

        if (!labIds.isEmpty()){
            List<Laboratory> laboratories = laboratoryService.listByIds(labIds);
            Map<Integer, String> labMap = laboratories.stream().collect(Collectors.toMap(Laboratory::getLaboratoryId, Laboratory::getLaboratoryName));
            model.addAttribute("labMap",labMap);
        }else{
            model.addAttribute("labMap", Collections.emptyMap());
        }
        return "user-info";
    }
    @GetMapping("/update")
    public String update( Model model, Authentication authentication) {
       log.info("查询个人信息回显");
        MyUserDetails userDetails = (MyUserDetails) authentication.getPrincipal();
        model.addAttribute("userDetails", userDetails);
        model.addAttribute("userInfo", userinfoService.lambdaQuery().eq(UserInfo::getUserId,userDetails.getId()).one());
        return "updateinfo";
    }
    @PostMapping("/update")
    public String update(
            @RequestParam("username") String username,
            @RequestParam("email") String email,
            @RequestParam("phone") String phoneNumber,
            @RequestParam("image") MultipartFile image,
            Authentication authentication) throws IOException {

        MyUserDetails userDetails = (MyUserDetails) authentication.getPrincipal();
        UserInfo userInfo = userinfoService.lambdaQuery()
                .eq(UserInfo::getUserId, userDetails.getId())
                .one();

        String imagePath = null;
        if (!image.isEmpty()) {
            imagePath = commonService.upload(image); // 调用 CommonService 的 upload 方法
            log.info("图片上传成功，路径: {}", imagePath);
        }
        User one = userService.lambdaQuery().eq(User::getUserId, userDetails.getId()).one();
        one.setUserName(username);
        userService.updateById(one);

        // 更新用户信息
        userInfo.setEmail(email);
        userInfo.setPhoneNumber(phoneNumber);
        userInfo.setImage(imagePath);


        // 保存用户信息
        userinfoService.updateById(userInfo);

        return "redirect:/user/userInfo";
    }
    //查询所有用户
    @GetMapping("/userlist")
    public String listUsers(Model model) {
        List<UserInfo> userList = userinfoService.list();
        model.addAttribute("userList", userList);
        return "user-list";
    }
    @GetMapping("/admin")
    @PreAuthorize("hasRole('admin')")
    public String admin(Authentication authentication, Model model){
        MyUserDetails userDetails = (MyUserDetails) authentication.getPrincipal();
        model.addAttribute("user", userDetails);
        return "admin";
    }




}
